from sqlalchemy.orm import Session
import app.sql.models as model
from . import security
from fastapi import HTTPException, status
from .. import exceptions

def get_user_by_id(db: Session, uid: int):
    return db.query(model.User).filter(model.User.id ==  uid).first()

def check_user_exists(db: Session, email: str):
    return db.query(model.User).filter(model.User.email == email).first()

def is_creditnail_valid(db: Session, email: str, password: str):
    user = check_user_exists(db, email)
    if user:
        if(security.match_passwords(password, user.hashed_password)):
            return security.create_access_token(user.id)
        else:
            raise exceptions.invalid_password_exception
    else:
        raise exceptions.user_dont_exist_exception


def add_user(db: Session, username: str, password: str):
    if not(check_user_exists(db, username)):
        db_user = model.User(email=username, hashed_password=security.hash_password(password))
        db.add(db_user)
        db.commit()
        return "ok"
    else:
        raise exceptions.user_already_exist_exception
